﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using WinDocker.Common.Global;

namespace WinDocker.Common.Helper.Udp
{
    public class UdpHelper
    {
        /// <summary>
        /// Udp数据广播发送
        /// </summary>
        /// <param name="message">数据内容</param>
        /// <param name="port">端口</param>
        /// <param name="broadcastIp">广播Ip</param>
        public static void Send(string message, int port = 9895, string broadcastIp = "255.255.255.255")
        {
            try
            {
                var udpClient = new UdpClient();
                // 设置广播地址和端口号
                IPAddress broadcastAddress = IPAddress.Parse(/*"255.255.255.255"*/broadcastIp);
                //port = 9895;

                // 启用广播
                udpClient.EnableBroadcast = true;

                //发送广播消息
                //string message = "Hello, world!";
                byte[] data = Encoding.UTF8.GetBytes(message);//注:默认全为UTF8编码格式
                udpClient.Send(data, data.Length, new IPEndPoint(broadcastAddress, port));
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"UdpHelper Send Err:{ex.Message}");
            }
        }

        /// <summary>
        /// 创建客户端
        /// </summary>
        //private static Socket Client;

        public static void ReceiveStart(int port = 9895/*, string broadcastIp =*/ /*"255.255.255.255"*//*"192.168.0.134"*/)
        {
            try
            {
                ///////创建客户端
                ////Client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                ////Client.Bind(new IPEndPoint(IPAddress.Parse(broadcastIp), port));


                System.Threading.Thread th = new System.Threading.Thread(ReceiveStartRun);
                th.Start(new object[] { port/*, broadcastIp*/ });
                //th.Start(Client);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"UdpHelper ReceiveStart Err:{ex.Message}");
            }
        }

        public delegate void ReceiveHandle(string str);
        /// <summary>
        /// 数据接收事件
        /// </summary>
        public static event ReceiveHandle ReceiveEvnt;

        private static void ReceiveStartRun(object obj)
        {
            try
            {
                //var client = (Socket)obj;
                /////用来保存发送方的ip和端口号
                //EndPoint point = new IPEndPoint(IPAddress.Any, 0);
                ////MessageBox.Show(point.ToString());
                /////定义客户端接收到的信息大小
                //byte[] buffer = new byte[1024 * 1024];
                /////接收到的信息大小(所占字节数)
                //int length = client.ReceiveFrom(buffer, ref point);
                //string message = Encoding.UTF8.GetString(buffer, 0, length);
                ////listBox1.Items.Add(point.ToString() + "：" + message);

                #region Old
                //var objArray = (object[])obj;
                //int port = (int)objArray[0];
                //string broadcastIp = (string)objArray[1];
                ////broadcastIp = "192.168.0.134";
                //var udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0));//new UdpClient();
                //// 设置广播地址和端口号
                //IPAddress broadcastAddress = IPAddress.Parse(/*"255.255.255.255"*/broadcastIp);
                ////port = 9895;

                ////启用广播
                ////udpClient.EnableBroadcast = true;

                //// 接收广播消息
                //IPEndPoint remoteEP = new IPEndPoint(/*IPAddress.Any*/broadcastAddress, port);
                ////udpClient.Connect(remoteEP);
                //while (true)
                //{
                //    byte[] receivedData = udpClient.Receive(ref remoteEP);
                //    string receivedMessage = Encoding.UTF8.GetString(receivedData);//注:默认全为UTF8编码格式
                //    if (ReceiveEvnt != null)
                //    {
                //        System.Threading.Thread th = new System.Threading.Thread((ob) =>
                //        {
                //            try
                //            {
                //                var revMsg = (string)ob;
                //                ReceiveEvnt(revMsg);
                //            }
                //            catch (Exception ex)
                //            {
                //                LogWrite.TxtExport_DateNow("LogErr.txt", $"UdpHelper ReceiveStartRun 0Err:{ex.Message}");
                //            }
                //        });
                //        th.Start(receivedMessage);
                //    }
                //}
                #endregion Old
                var objArray = (object[])obj;
                int port = (int)objArray[0];
                //创建UdpClient实例
                UdpClient udpClient = new UdpClient();
                //指定接收端口为所有IP地址的固定端口
                udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, /*9895*/port));
                var remoteEP = new IPEndPoint(IPAddress.Any, 0);
                //接收消息
                while (true)
                {
                    byte[] receiveBytes = udpClient.Receive(ref remoteEP);
                    string receivedMessage = Encoding.UTF8.GetString(receiveBytes);
                    //Console.WriteLine("Received message: {0}", receiveStr);
                    if (ReceiveEvnt != null)
                    {
                        System.Threading.Thread th = new System.Threading.Thread((ob) =>
                        {
                            try
                            {
                                var revMsg = (string)ob;
                                ReceiveEvnt(/*"[[d]]\r\n" +*/ revMsg);
                            }
                            catch (Exception ex)
                            {
                                LogWrite.TxtExport_DateNow("LogErr.txt", $"UdpHelper ReceiveStartRun 0Err:{ex.Message}");
                            }
                        });
                        th.Start(receivedMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"UdpHelper ReceiveStartRun Err:{ex.Message}");
            }

        }

    }
}
